package com.javacrimefighter.gwt.activemq.client;

public class ActiveMQ {

    private int nextId = 1;
    
    public ActiveMQ(String uri) {
        init(uri);
    }
    
    private static native void init(String uri) /*-{
        $wnd.amq.uri = uri
    }-*/;
    
    public native void send(String destination, String message) /*-{
        $wnd.amq.sendMessage(destination,message) 
    }-*/; 
    
    public MessageHandlerRegistration subscribe(String destination, MessageHandler<?> handler) {
        final String id = Integer.toString(nextId++);
        doSubscribe(id,destination, handler);
        return new MessageHandlerRegistration() {
            public void removeHandler() {
                unsubscribe(id);
            }
        };
    }
    
    private native static void doSubscribe(String id, String destination, MessageHandler<?> handler) /*-{
        var callback = {
            receive: function(message) {
                try {
                    handler.@com.javacrimefighter.gwt.activemq.client.MessageHandler::onMessage(Lcom/google/gwt/core/client/JavaScriptObject;)(message);
                } catch (e) {
                    $wnd.alert('exception: ' + e)
                }
            }
        };
        $wnd.amq.addListener(id,destination,callback.receive);
    }-*/;

    private native void unsubscribe(String id) /*-{
        $wnd.amq.removeHandler(id);
    }-*/;
}
